Skip to content

Fix unable to import in node 12.18 ESM#77

Merged
guybedford merged 3 commits into
guybedford:mainfrom
marvinhagemeister:esm
Jul 5, 2021
Merged

Fix unable to import in node 12.18 ESM#77
guybedford merged 3 commits into
guybedford:mainfrom
marvinhagemeister:esm

Conversation

@marvinhagemeister

@marvinhagemeister marvinhagemeister commented Jul 5, 2021

Copy link
Copy Markdown
Contributor

This PR adds some fields to package.json to be able to use this library with native ESM mode in node 12.18 and upwards. Without these node fails with the following error:

(node:1744) ExperimentalWarning: The ESM module loader is experimental.
file:///opt/build/repo/packages/wmr/src/lib/transform-imports.js:1
import { parse } from 'es-module-lexer';
         ^^^^^
SyntaxError: The requested module 'es-module-lexer' does not provide an export named 'parse'
    at ModuleJob._instantiate (internal/modules/esm/module_job.js:92:21)
    at async ModuleJob.run (internal/modules/esm/module_job.js:107:20)
    at async Loader.import (internal/modules/esm/loader.js:179:24)

Ran into this while working on preactjs/wmr#715 .

Explanation of the fix:

"exports": {
  // Main/default entry point
  ".": {
    "import": "./dist/lexer.js",
    // CommonJS entry point
    "require": "./dist/lexer.cjs"
  },
  // If any module wants to import `es-module-lexerpackage.json` for some reason
  // (grabbing package.version or something)
  "./package.json": "./package.json",
  // Old-style deep imports, like `require("es-module-lexer/dist/lexer.js")`
  "./": "./"
},

Fixes #54 .

@guybedford guybedford left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR.

I also just noticed this one myself. The issue here is Node.js 12.18 doesn't yet supported the named exports for CJS feature, and as a result the package must be imported via import lexer from 'es-module-lexer'.

Fixing this via conditional exports seems good to me.

Comment thread package.json Outdated
Co-authored-by: Guy Bedford <guybedford@gmail.com>

@guybedford guybedford left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, merging and releasing now.

Comment thread package.json Outdated
@guybedford
guybedford merged commit 4a3a22b into guybedford:main Jul 5, 2021
@marvinhagemeister
marvinhagemeister deleted the esm branch July 5, 2021 17:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

node exports?

2 participants